var get = require('../../utils/getRequest');
var post = require('../../utils/postRequest');
const api = require('../../utils/api')
const mqtt = require('../../utils/mqtt.js')
let client = null;
let ctx
Page({
  data: {
    connectFlag: false,
    TX: '', ///TX/LR90000000001
    RX: '', ///RX/LR90000000001
    deviceListData: [],
    deviceSn: null,
    productList: [],
    deviceMsg: null,
    sheetShow: false,
    sheetActions: [{
        id: '01',
        name: '在线支付'
      },
      {
        id: '02',
        name: '信用分支付'
      }
    ],
    twoballLog: api.twoballLog,
    ball01Log: api.ball01Log,
    ball02Log: api.ball02Log,
    salesGridList: [],
    rentGridList: [],
    showRentGridList: [],
    giveBackList: [],
    popupShow: false,
    buyHtml: '',
    buyItem: null,
    rentHtml: '',
    rentItem: null,
    dealType: null,
    giveBackIndex: null,
    errorBallTimes: 1
  },
  onLoad(options) {
    if (api.openId == null) {
      wx.login({
        success: (res) => {
          var code = res.code;
          var data = {
            code: code
          };
          get.getRequest(null, api.getOpenIdByCode, data).then(res => {
            console.log("res.code:", res.code)
            console.log("res.data.openId:", res.data.openId)
            if (res.code == 200) {
              api.openId = res.data.openId;
            }
          })
        },
      })
    }
    var deviceSn = options.deviceSn;
    const lastFourChars = deviceSn.substr(deviceSn.length - 8);
    var TX = '/TX/LR900' + lastFourChars;
    var RX = '/RX/LR900' + lastFourChars;
    ctx = this
    ctx.setData({
      deviceSn: deviceSn,
      TX: TX,
      RX: RX
    });
  },
  onShow(res) {
    if (res && res.scene === 1038) {
      const {
        appId,
        extraData
      } = res.referrerInfo;
    }
    this.initMqtt();
    get.getRequest(null, api.getAllProductList, {}).then(res => {
      ctx.setData({
        productList: res.data
      });
      ctx.getDevice();
    });
  },
  initMqtt() {
    var url = "wxs:device.x-washer.com/mqtt";
    console.log("服务器地址：" + url);
    let randomNum = Math.floor(Math.random() * 100000000000)
    // 连接选项
    const options = {
      connectTimeout: 4000, // 超时时间
      // 认证信息 按自己需求填写
      clientId: 'wx' + randomNum,
      username: 'x-washer01',
      password: '123456Qwe',
    }
    var that = this;
    if (!client) {
      client = null
    }
    //client = mqtt.connect('wxs:www.x-washer.com/mqtt', options);
    client = mqtt.connect(url, options);
    client.on('reconnect', (error) => {
      //that.setData({connectFlag:false})
      console.log('正在重连:', error)
    });
    client.on('connect', (e) => {
      console.log('成功连接服务器111')
      client.publish(that.data.RX, "{SQLID}");
      //订阅一个主题
      client.subscribe(this.data.TX, {
        qos: 1
      }, function (err) {
        if (!err) {

          console.log("订阅成功")
          console.log("写入数据：" + that.data.RX)
          client.publish(that.data.RX, "{SQLID}");
        }

      })
    })
    client.on('error', (error) => {
      that.setData({
        connectFlag: false
      })
      console.log('连接失败:', error)
    })
    //监听mq的返回
    client.on('message', function (topic, message, packet) {
      var data = packet.payload.toString();
      var mydata = data.replace("[{", "[");
      mydata = mydata.replace('"id:"', '"id":"');
      var obj = JSON.parse(mydata);
      console.log('监听后的数据',obj);
      if (obj.type == "3" && ctx.data.errorBallTimes <= 0) { //读取全部格子状态
        ctx.initShowRentGridList(obj);
        ctx.initgiveBackList(obj);
      }
      if (obj.type == "3" && ctx.data.errorBallTimes > 0) {
        ctx.dealErrorRentBall(obj);
      }
      if (obj.type == "2" && ctx.data.giveBackIndex != null) { //单个格子状态上报
        ctx.dealGiveBackBall(obj);
      }
      that.setData({
        connectFlag: true
      });
      if (obj.type != "3") {
        var commd = "{SQLID}";
        client.publish(ctx.data.RX, commd);
      }
      //client.end()
    })
  },
  getDevice() {
    var data = {
      deviceSn: ctx.data.deviceSn
    }
    get.getRequest(null, api.getDeviceByDeviceSn, data).then(res => {
      ctx.setData({
        deviceMsg: res.data
      });
      ctx.initSalesGrid();
      ctx.initRentGrid();
    });
  },
  initSalesGrid() { //初始化出售的格子
    var salesGridList = [];
    var deviceMsg = ctx.data.deviceMsg;
    var gridNumber = deviceMsg.gridNumber;
    console.log("格子数量A：" + gridNumber);
    var j = 0;
    for (var i = 1; i <= gridNumber; i++) {
      var prefix = '';
      if (i < 10) {
        prefix = "grid0";
      } else {
        prefix = "grid";
      }
      var name01 = prefix + i + "StateType";
      var stateType = deviceMsg[name01];
      if (stateType != "1") continue;
      var name02 = prefix + i + "ProductId";
      var productIdStr = deviceMsg[name02];
      var arry = productIdStr.split(",");
      var arry01 = arry[0];
      var arry02 = arry[1];
      if (arry01 != "1") continue;
      var obj = ctx.getProductMsg(arry02, i);
      let newObj = Object.assign({}, obj);
      salesGridList.push(newObj);
    }
    console.log("销售的格子：", salesGridList);
    ctx.setData({
      salesGridList: salesGridList
    });
  },
  initRentGrid() { //初始化租用的格子
    var rentGridList = [];
    var deviceMsg = ctx.data.deviceMsg;
    var gridNumber = deviceMsg.gridNumber;
    console.log("格子数量B：" + gridNumber)
    for (var i = 1; i <= gridNumber; i++) {
      var name01 = "grid0" + i + "StateType";
      if (i < 10) {
        name01 = "grid0" + i + "StateType";
      } else {
        name01 = "grid" + i + "StateType"
      }
      var stateType = deviceMsg[name01];
      if (stateType != "1") continue;
      var name02 = "";
      if (i < 10) {
        name02 = "grid0" + i + "ProductId";
      } else {
        name02 = "grid" + i + "ProductId";
      }
      var productIdStr = deviceMsg[name02];
      var arry = productIdStr.split(",");
      var arry01 = arry[0];
      var arry02 = arry[1];
      if (arry01 != "2") continue;
      var obj = ctx.getProductMsg(arry02, i);
      let newObj = Object.assign({}, obj);
      rentGridList.push(newObj)
    }
    console.log("不显示所有出租的格子：", rentGridList);
    ctx.setData({
      rentGridList: rentGridList
    });
  },
  initShowRentGridList(obj) { //初始化显示可以租用的格子
    var rentGridList = this.data.rentGridList;
    var gridList = obj.data;
    var showRentGridList = [];
    console.log("所有租用的格子：");
    console.log(rentGridList);
    console.log("传入的obj：" + obj);
    for (var i = 0; i < gridList.length; i++) {
      if (gridList[i].state != "6") continue;
      for (var j = 0; j < rentGridList.length; j++) {
        if (i == (rentGridList[j].index - 1)) {
          var obj = rentGridList[j];
          obj.num = gridList[i].num;
          let newObj = Object.assign({}, obj);
          showRentGridList.push(newObj);
          break;
        }
      }
    }
    console.log("ssssssssssssssssss");
    console.log("显示租用的格子对象：", showRentGridList);
    ctx.setData({
      showRentGridList: showRentGridList
    })
  },
  initgiveBackList(obj) { //初始化可以归还的格子
    var rentGridList = this.data.rentGridList;
    var gridList = obj.data;
    var giveBackList = [];
    for (var i = 0; i < gridList.length; i++) {
      if (gridList[i].state != "1" && gridList[i].state != "2") continue;
      for (var j = 0; j < rentGridList.length; j++) {
        if (i == (rentGridList[j].index - 1)) {
          var obj = rentGridList[j];
          obj.num = gridList[i].num;
          let newObj = Object.assign({}, obj);
          giveBackList.push(newObj);
          break;
        }
      }
    }
    console.log("ssssssssssssssssss");
    console.log("归还的格子：", giveBackList);
    ctx.setData({
      giveBackList: giveBackList,
      // showRentGridList: giveBackList,
    })
  },
  getProductMsg(productId, index) {
    var productList = ctx.data.productList
    for (var i = 0; i < productList.length; i++) {
      if (productId == productList[i].productId) {
        productList[i].index = index;
        productList[i].name = "" + ctx.gridName(index);
        return productList[i];
      }
    }
    return null;
  },
  gridName(index) {
    return ['①', '②', '③', '④', '⑤', '⑥', '⑦', '⑧', '⑨', '⑩', '⑪', '⑫'][index - 1];
  },
  openRentBallDetail(event) {
    var rentHtml = event.currentTarget.dataset.item.productDesc;
    var rentItem = event.currentTarget.dataset.item;
    console.log("rentHtml:", rentHtml);
    console.log("rentItem:", rentItem);
    rentHtml = rentHtml.replace(/<img/gi, '<img style="max-width:100%;height:auto;display:block" ');
    this.setData({
      rentHtml: rentHtml,
      rentItem: rentItem,
      dealType: "2",
      popupShow: true
    });
  },
  rentBall(event) {
    var antecedentMoney = event.currentTarget.dataset.item.antecedentMoney;
    var data = {
      deviceSn: ctx.data.deviceSn,
      washballSn: event.currentTarget.dataset.item.num,
      index: event.currentTarget.dataset.item.index,
      openId: api.openId,
      perhourPrice: event.currentTarget.dataset.item.productPrice,
      payType: 'payscore'
    }
    // wx.showModal({
    //   title: '提示信息',
    //   showCancel: true,
    //   content: "收取" + antecedentMoney + "元押金，归还扣除租金后将退回剩余的金额",
    //   success(res) {
    //     if (res.confirm) {
    //       ctx.tenancy(data);
    //     }
    //   }
    // })
    ctx.tenancy(data);
  },
  async tenancy(data) {
    const res = await get.getRequest(null, api.initRentPay, data)
    var extraData = {
      mch_id: res.data.mchId,
      package: res.data.package,
      timestamp: res.data.timestamp,
      sign_type: res.data.signType,
      nonce_str: res.data.nonceStr,
      sign: res.data.paySign
    };
    wx.openBusinessView({
      businessType: 'wxpayScoreUse',
      extraData,
      success(res) {
        console.log('租用成功打印',res);
        if(res.extraData.query_id){
          var commd = '';
          var index = data.index;
          if (index < 10) {
            commd = '{\"lock\":\"0' + index + '\"' + '}';
          } else {
            commd = '{\"lock\":\"' + index + '\"' + '}';
          }
          client.publish(ctx.data.RX, commd);
          ctx.onPopupClose();
        }
      },
      fail(res) {
        console.log('租用失败');
      },
    })
  },
  launchRentBallPay(data) {
    get.getRequest(null, api.initRentPay, data).then(res => {
      if (res.code == 200) {
        wx.requestPayment({
          timeStamp: res.data.timeStamp,
          nonceStr: res.data.nonceStr,
          package: res.data.package,
          signType: res.data.signType,
          paySign: res.data.paySign,
          success(res) {
            var commd = '';
            var index = data.index;
            if (index < 10) {
              commd = '{\"lock\":\"0' + index + '\"' + '}';
            } else {
              commd = '{\"lock\":\"' + index + '\"' + '}';
            }
            client.publish(ctx.data.RX, commd);
            ctx.onPopupClose();
          },
          fail(res) {}
        })
      } else {
        wx.showModal({
          title: '提示信息',
          showCancel: true,
          content: res.msg
        })
      }
    })
  },
  openBuyBallDetail(event) {
    var buyHtml = event.currentTarget.dataset.item.productDesc;
    var buyItem = event.currentTarget.dataset.item;
    console.log("html:", buyHtml);
    console.log("buyItem:", buyItem);
    buyHtml = buyHtml.replace(/<img/gi, '<img style="max-width:100%;height:auto;display:block" ');
    this.setData({
      buyHtml: buyHtml,
      buyItem: buyItem,
      dealType: "1",
      popupShow: true
    });
  },
  buyBall(event) {
    console.log("buyBall:", event);
    var connectFlag = ctx.data.connectFlag;
    if (!connectFlag) {
      wx.showToast({
        title: '设备断开了连接',
      })
      return;
    }
    var data = {
      deviceSn: ctx.data.deviceSn,
      index: event.currentTarget.dataset.item.index,
      productId: event.currentTarget.dataset.item.productId,
      openId: api.openId
    }
    var html = event.currentTarget.dataset.item.productDesc;
    console.log("html:", html);
    html = html.replace(/<img/gi, '<img style="max-width:100%;height:auto;display:block" ');
    this.setData({
      html: html
    });
    get.getRequest(null, api.initBuyPay, data).then(res => {
      if (res.code == 200) {
        console.log(res);
        wx.requestPayment({
          timeStamp: res.data.timeStamp,
          nonceStr: res.data.nonceStr,
          package: res.data.package,
          signType: res.data.signType,
          paySign: res.data.paySign,
          success(res) {
            var commd = "";
            var index = event.currentTarget.dataset.item.index;
            if (index < 10) {
              commd = '{\"lock\":\"0' + index + '\"' + '}';
            } else {
              commd = '{\"lock\":\"' + index + '\"' + '}';
            }
            console.log("commd======" + commd);
            ctx.onPopupClose();
            client.publish(ctx.data.RX, commd);
            ctx.updateBuyForDevice(index);
          },
          fail(res) {}
        })
      }
    })
  },
  updateBuyForDevice(index) {
    var newsalesGridList = [];
    var salesGridList = ctx.data.salesGridList;
    var deviceType = this.data.deviceMsg.deviceType;
    console.log("deviceType========" + deviceType);
    for (var i = 0; i < salesGridList.length; i++) {
      if (index == salesGridList[i].index) continue;
      newsalesGridList.push(salesGridList[i]);
    }
    console.log("newsalesGridList" + newsalesGridList);
    ctx.setData({
      salesGridList: newsalesGridList
    });
    var data = {
      deviceSn: ctx.data.deviceSn,
      index: index
    }
    if (deviceType == "1") {
      get.getRequest(null, api.saveDeviceBallBuyState, data).then(res => {
        console.log("---------------");
        console.log(res);
      })
    }
  },
  openPopup(event) {
    this.setData({
      popupShow: true
    })
  },
  onPopupClose() {
    this.setData({
      popupShow: false
    })
  },
  giveBackBall(event) {
    var giveBackIndex = event.currentTarget.dataset.item.index;
    wx.showModal({
      title: '提示信息',
      showCancel: true,
      content: "点击确认后，不要离开本页面，将打格子，把租用的洗衣球放进去选择的格子中，充上电并关上锁",
      success(res) {
        if (res.confirm) {
          var commd = "";
          ctx.setData({
            giveBackIndex: giveBackIndex
          });
          if (giveBackIndex < 10) {
            commd = '{\"lock\":\"0' + giveBackIndex + '\"' + '}';
          } else {
            commd = '{\"lock\":\"' + giveBackIndex + '\"' + '}';
          }
          client.publish(ctx.data.RX, commd);
          wx.showLoading({
            title: '等待处理中',
          })
        }
      }
    });
  },
  async ball(data){
    var data = {
      washballSn: '0000000000',
      deviceSn: '13889887',
      openId: api.openId
    }
    const res = await get.getRequest(null, api.dealGiveBackBall, data)
    console.log(res);
  },
  dealGiveBackBall(obj) {
    var state = obj.state;
    var id = obj.id;
    var washballSn = obj.num;
    var giveBackIndex = "0" + this.data.giveBackIndex;
    var deviceSn = this.data.deviceSn;
    if (id == giveBackIndex && state == "5" || state == "6") {

      var data = {
        washballSn: washballSn,
        deviceSn: deviceSn,
        openId: api.openId
      }
      get.getRequest(null, api.dealGiveBackBall, data).then(res => {
        if (res.code == 200) {
          wx.showModal({
            title: '提示信息',
            showCancel: false,
            content: res.msg,
            success(res) {
              if (res.confirm) {
                ctx.setData({
                  giveBackIndex: null
                });
                var commd = "{SQLID}";
                client.publish(ctx.data.RX, commd);
              }
            }
          });
        } else {
          wx.showModal({
            title: '提示信息',
            showCancel: false,
            content: res.msg,
            success(res) {
              if (res.confirm) {
                ctx.setData({
                  giveBackIndex: null
                });
                var commd = "";
                if (giveBackIndex < 10) {
                  commd = '{\"lock\":\"0' + giveBackIndex + '\"' + '}';
                } else {
                  commd = '{\"lock\":\"' + giveBackIndex + '\"' + '}';
                }
                client.publish(ctx.data.RX, commd);
              }
            }
          });
        }
      }).finally(res => {
        wx.hideLoading()
      });
    }
  },
  dealErrorRentBall(obj) {
    var list = obj.data;
    var dealList = [];
    var test = [];
    for (var i = 0; i < list.length; i++) {
      test.push(list[i].num);
      if (list[i].state == "5" || list[i].state == "6") {
        dealList.push(list[i].num);
      }
    }
    console.log("球的编号A：", test)
    if (dealList.length > 0) {
      var washballSnStr = "";
      for (var i = 0; i < dealList.length; i++) {
        washballSnStr = washballSnStr + dealList[i] + ",";
      }
      console.log("球的编号：", washballSnStr)
      var deviceSn = this.data.deviceSn;
      var data = {
        washballSnStr: washballSnStr,
        deviceSn: deviceSn,
        openId: api.openId
      }
      wx.showLoading({
        title: '检查历史订单中',
      })
      get.getRequest(null, api.dealErrorRentBallList, data).then(res => {
        console.log("检查订单：", res);
        console.log("检查订单：", res.code);
        if (res.code == 200) {
          ctx.setData({
            errorBallTimes: 0
          });
          client.publish(ctx.data.RX, "{SQLID}");
        }
      }).finally(res => {
        wx.hideLoading();
      })
    } else {
      ctx.setData({
        errorBallTimes: 0
      });
      client.publish(ctx.data.RX, "{SQLID}");
    }
  },
})